module.exports = class extends think.Model {
  async creditupdate(userid, cost) {
    console.log(cost);
    const user = this.model('user');
    const user_level = await user
      .where({
        id: userid
        //   user_level_id: 2
      })
      .getField('user_level_id', true);
    const rate = await this.model('user_level')
      .where({ id: user_level })
      .getField('credit_rate', true);
    const data = await user
      .where({
        id: userid
      })
      .increment({
        credit: cost * rate,
        spend_total: cost
      });
    const spend_total = await user
      .where({
        id: userid
      })
      .getField('spend_total', true);
    const result = await user
      .where({
        id: userid
      })
      .update({
        user_level_id:
          user_level != 2 && spend_total >= 79 ? 2 : ['exp', 'user_level_id+0']
      });
    return result;
  }
  async distribution(orderid) {
    const query = `SELECT IFNULL(vd.user_id ,0) AS id ,if(g.distribution_type="fixed",1,0.01) as unit ,IFNULL(sum(og.retail_price*og.number) ,0) as balance FROM nideshop_goods as g INNER JOIN nideshop_order_goods as og on g.id=og.goods_id INNER JOIN nideshop_video as vd ON og.track_id= vd.trackid where og.order_id=${orderid} and og.is_withdraw=0`;
    // const order = await this.model('goods')
    //   .alias('g')
    //   .field(['vd.user_id as id', 'if(g.distribution_type="fixed",1,0.01) as unit ' `sum(og.retail_price*og.number) as balance`])
    //   .join({
    //     table: 'order_goods',
    //     join: 'inner',
    //     as: 'og',
    //     on: ['og.goods_id', 'g.id']
    //   })
    //   .join({
    //     table: 'video',
    //     join: 'inner',
    //     as: 'vd',
    //     on: ['og.track_id', 'vd.trackid']
    //   })
    //   .where({
    //     'og.is_withdraw': 0,
    //     'og.order_id': orderid
    //   })
    //   .group('vd.user_id')
    //   .select();
    const order = await this.query(query);
    order.map(val => {
      val.balance = ['exp', `balance+${val.balance * val.unit}`];
    });
    const result = await this.updateMany(order.filter(val => val.id > 0));
    return result;
  }
};
